package com.colorful.insuranceproject.commonActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.adapter.PayMethodListAdapter;
import com.colorful.insuranceproject.base.TitleActivity;
import com.colorful.insuranceproject.bean.AliPayBean;
import com.colorful.insuranceproject.bean.LianLianBean;
import com.colorful.insuranceproject.bean.PayMethod;
import com.colorful.insuranceproject.bean.PaySuccessBean;
import com.colorful.insuranceproject.bean.PaymentBean;
import com.colorful.insuranceproject.bean.WeChatPayBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.mine.PaySuccessActivity;
import com.colorful.insuranceproject.request.HomeRequest;
import com.lovely3x.common.adapter.ListAdapter;
import com.lovely3x.common.managements.pay.IPayCallBack;
import com.lovely3x.common.managements.pay.PayRequest;
import com.lovely3x.common.managements.pay.PaymentManager;
import com.lovely3x.common.managements.user.TokenManager;
import com.lovely3x.common.utils.Response;
import com.lovely3x.common.widgets.EnoughHeightListView;
import com.lovely3x.paymentlibrary.alipay.AliPayPayRequest;
import com.lovely3x.paymentlibrary.lianlian.utils.BaseHelper;
import com.lovely3x.paymentlibrary.lianlian.utils.LianLianPayRequest;
import com.lovely3x.paymentlibrary.lianlian.utils.PayOrder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/8/19.
 * <p>
 * 支付页面
 */
public class PaymentActivity extends TitleActivity implements ListAdapter.OnItemClickedListener<PayMethod> {

    /**
     * 确认订单支付成功
     */
    private static final int MAKE_SURE_THE_ORDER_PAYMENT_SUCCESSFUL = 0X5;

    /**
     * 获取到微信支付的TN对象
     */
    private static final int GET_WE_CHAT_PAY_TN_URL = 0X6;

    /**
     * 获取连连支付的TN对象
     */
    private static final int GET_LIAN_LIAN_PAY_URL = 0X7;

    /**
     * 获取支付宝的TN
     */
    private static final int GET_ALI_PAY_TN_URL = 0X8;

    /**
     * 输入支付密码
     */
    private static final int REQUEST_CODE_INPUT_PAY_PASSWORD = 0X9;

    /**
     * 支付列表
     */
    private PayMethodListAdapter mPayMethodListAdapter;

    /**
     * 传递的页面数据
     */
    public static final String EXTRA_BEAN_DATA = "extra_payment_bean_data";

    /**
     * 应付总额
     */
    @Bind(R.id.tv_sum_payable)
    TextView tvSumPayable;

    /**
     * 支付选择
     */
    @Bind(R.id.lv_pay_type)
    EnoughHeightListView lvPayType;

    /**
     * 商品总额
     */
    @Bind(R.id.tv_goods_all_money)
    TextView tvGoodsAllMoney;

    /**
     * 运费总额
     */
    @Bind(R.id.tv_total_amount_of_tp)
    TextView tvTotalAmountOfTp;

    /**
     * 优惠券
     */
    @Bind(R.id.tv_coupon_srf)
    TextView tvCouponSrf;

    /**
     * 可乐余额
     */
    @Bind(R.id.tv_color_balance_srf)
    TextView tvColorBalanceSrf;

    /**
     * 实付
     */
    @Bind(R.id.tv_all_total)
    TextView tvAllTotal;

    /**
     * 最后的支付金额
     */
    @Bind(R.id.tv_final_pay)
    TextView tvFinalPay;

    /**
     * 支付按钮
     */
    @Bind(R.id.tv_pay)
    TextView tvPay;

    /**
     * 判断页面支付返回后的状态
     */
    private int resumeType;

    java.text.DecimalFormat df;

    private HomeRequest homeRequest;

    /**
     * 支付方式
     */
    int payFrom;

    private PaymentBean paymentBean;

    @Override
    protected int getContentView() {
        return R.layout.activity_payment;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setTitle(getString(R.string.pay));
    }

    @Override
    protected void onInitExtras(@NonNull Bundle bundle) {
        super.onInitExtras(bundle);
        paymentBean = bundle.getParcelable(EXTRA_BEAN_DATA);
    }

    @Override
    protected void onViewInitialized() {
        df = new java.text.DecimalFormat("######0.00");
        homeRequest = new HomeRequest(getHandler());

        //  支付列表的适配器
        this.mPayMethodListAdapter = new PayMethodListAdapter(makeMethodList(), this);
        lvPayType.setAdapter(mPayMethodListAdapter);
        mPayMethodListAdapter.setOnItemClickedListener(this);

        //还需支付
        tvFinalPay.setText(getString(R.string.price_and_postmoney, paymentBean.getNeedPay()));

        //商品总额
        tvGoodsAllMoney.setText(getString(R.string.price_and_postmoney, df.format(Float.parseFloat(paymentBean.getGoodsMoney()))));

        //运费总额
        if (paymentBean.getDeliverMoney() == null || paymentBean.getDeliverMoney().equals("") || paymentBean.getDeliverMoney().equals("null")) {
            tvTotalAmountOfTp.setText(getString(R.string.price_and_postmoney, "0.00"));
        } else {
            tvTotalAmountOfTp.setText(getString(R.string.price_and_postmoney, df.format(Float.parseFloat(paymentBean.getDeliverMoney()))));
        }

        //实付
        tvAllTotal.setText(df.format(Float.parseFloat(paymentBean.getNeedPay())));
    }

    /**
     * 初始化支付回调
     */
    private void initPay() {
        PaymentManager.getInstance().registerPaymentCallBack(new IPayCallBack() {
            @Override
            public void onPayResult(PayMethod payMethod, PayResult payResult) {
                PaymentManager.getInstance().unregisterPaymentCallBack(this);
                switch (payResult) {
                    case Fail: {
                        resumeType = 1;
                        payError();
                    }
                    break;
                    case UserCancel: {
                        resumeType = 1;
                        payError();
                    }
                    break;
                    case Waiting: {
                        setResult(RESULT_OK);
                        finish();
                    }
                    break;
                    case Successful: {
                        if (paymentBean != null) {
                            //{"goodsMoney":25.80,"deliverMoney":0.00,"useScore":0.00,"
                            // orderNo":"151186015422875696",
                            // "isBatch":1,"userId":240422,"needPay":25.80,"kekanganEDu":0.00}}
                            homeRequest.makeSureTheOrderPaymentSuccessful(paymentBean.getOrderNo(), paymentBean.getOrderNo(), "3",
                                    payFrom, MAKE_SURE_THE_ORDER_PAYMENT_SUCCESSFUL);
                        }
                    }
                    break;
                }
            }
        });
    }

    /**
     * 创建支付方式列表
     */
    protected List<PayMethod> makeMethodList() {
        //  初始化支付回调
        initPay();
        ArrayList<PayMethod> methods = new ArrayList<>();
//        支付方式 0：余额 1：支付宝 2：微信  3：连连支付 4:可康安支付
        methods.add(new PayMethod("1", getString(R.string.alipay_paymnet), R.drawable.icon_zhifubao_pay, true, 0));
        methods.add(new PayMethod("2", getString(R.string.wechat_pay), R.drawable.icon_weixin_pay, true, 0));
        if (paymentBean.getKekanganEDu() < Float.parseFloat(paymentBean.getNeedPay())) {
            methods.add(new PayMethod("4", getString(R.string.appname), R.drawable.icon_kekangan_gray, false, paymentBean.getKekanganEDu()));
        } else {
            methods.add(new PayMethod("4", getString(R.string.appname), R.drawable.icon_kekangan, true, paymentBean.getKekanganEDu()));
        }

        return methods;
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            //  获取微信支付的TN
            case GET_WE_CHAT_PAY_TN_URL:
                dismissProgressCircle();
                tvPay.setClickable(true);
                if (response.isSuccessful) {
                    callWeChatPay((List<WeChatPayBean>) response.obj);
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            //  获取支付宝
            case GET_ALI_PAY_TN_URL:
                dismissProgressCircle();
                tvPay.setClickable(true);
                if (response.isSuccessful) {
                    callAliPay((AliPayBean) response.obj);
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            //  获取连连支付的TN
            case GET_LIAN_LIAN_PAY_URL:
                dismissProgressCircle();
                tvPay.setClickable(true);
                if (response.isSuccessful) {
                    LianLianBean lianBean = (LianLianBean) response.obj;
                    callLianLianPay(lianBean.getSignResult());
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            // 验证订单支付成功 并修改本地数据库
            // 验证支付密码并支付订单
            case MAKE_SURE_THE_ORDER_PAYMENT_SUCCESSFUL:
                tvPay.setClickable(true);
                dismissProgressCircle();
                if (response.isSuccessful) {
                    modifyLocalDataBase((PaySuccessBean) response.obj);
                } else {
                    if (!CodeTable.getInstance().getCodeDescription(response).equals("payFrom参数有误")) {
                        showToast(CodeTable.getInstance().getCodeDescription(response));
                    }
                    if (payFrom == 4) {
                        showToast(CodeTable.getInstance().getCodeDescription(response));
                    }
                }
                break;
        }
    }

    /**
     * 支付成功 页面跳转
     */
    private void modifyLocalDataBase(PaySuccessBean obj) {
        launchActivityForResult(PaySuccessActivity.class, 10000, PaySuccessActivity.EXTRA_BEAN, obj);
    }

    /**
     * 调用微信支付
     */
    private void callWeChatPay(List<WeChatPayBean> list) {
        WeChatPayBean obj = list.get(0);
        PaymentManager.getInstance().sendPaymentRequest(
                new PayRequest(obj.getOut_trade_no(), obj.getOut_trade_no(), obj.getSign(), obj.getPartnerid(), obj.getPrepayid(), obj.getNoncestr(), obj.getTimestamp())
                , IPayCallBack.PayMethod.WeChatPay);
    }

    /**
     * 调用支付宝支付
     */
    private void callAliPay(AliPayBean obj) {
        PaymentManager.getInstance().sendPaymentRequest(
                new AliPayPayRequest(PaymentActivity.this, obj.getSignResult(), obj.getSignResult(), obj.getSignResult(), obj.getSignResult())
                , IPayCallBack.PayMethod.AliPayServerSign);
    }

    /**
     * 调用连连支付
     */
    private void callLianLianPay(PayOrder obj) {
        String llInfo = BaseHelper.toJSONString(obj);
        PaymentManager.getInstance().sendPaymentRequest(
                new LianLianPayRequest(PaymentActivity.this, llInfo, llInfo, llInfo, llInfo, llInfo, llInfo, llInfo, llInfo)
                , IPayCallBack.PayMethod.LianLainPay);
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    /**
     * 页面监听处理方式
     */
    @OnClick({R.id.tv_pay})
    void onClicked(View view) {
        switch (view.getId()) {
            //  去付款
            case R.id.tv_pay:
                String payMethodId = mPayMethodListAdapter.findCheckedItem();
                PayMethod selectedPayMethod = null;

                for (PayMethod payMethod : mPayMethodListAdapter.getDatas()) {
                    if (payMethod.typeId.equals(payMethodId)) {////选择的支付方式
                        selectedPayMethod = payMethod;
                        break;
                    }
                }

                if (selectedPayMethod == null) {
                    new AlertDialog.Builder(mActivity)
                            .setTitle(getString(R.string.hint))
                            .setMessage(getString(R.string.please_choose_pay_method))
                            .setPositiveButton(getString(R.string.sure), null).show();
                } else {

                    payFrom = Integer.parseInt(selectedPayMethod.typeId);
                    int isBatch = paymentBean.getIsBatch();
                    switch (payFrom) {
                        case 1:
                            showProgressCircle();
                            homeRequest.getAliPayData(paymentBean.getOrderNo(), isBatch, TokenManager.getInstance().getTokeValue(), GET_ALI_PAY_TN_URL);
                            break;
                        case 2:
                            showProgressCircle();
                            homeRequest.getWeChatPayData(paymentBean.getOrderNo(), isBatch, GET_WE_CHAT_PAY_TN_URL);
                            break;
                        case 4:
                            launchActivityForResult(PaymentPasswordInputActivity.class, REQUEST_CODE_INPUT_PAY_PASSWORD);//输入支付密码,进行支付
                            break;
                        //{"goodsMoney":25.80,"deliverMoney":0.00,"useScore":0.00,"
                        // orderNo":"151186015422875696",
                        // "isBatch":1,"userId":240422,"needPay":25.80,"kekanganEDu":0.00}}
                    }
                }
                break;
        }
    }

    @Override
    public void onClicked(int position, PayMethod payMethod) {
        if (payMethod.isAvailable) {
            if (mPayMethodListAdapter.isChecked(payMethod.typeId)) {
                mPayMethodListAdapter.check(payMethod.typeId, false);
                mPayMethodListAdapter.notifyDataSetChanged();
            } else {
                mPayMethodListAdapter.check(payMethod.typeId, true);
                mPayMethodListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (resumeType == 1) {
            payError();
        }
    }

    private void payError() {
        if (resumeType == 1) {
            try {
                AlertDialog.Builder alert = new AlertDialog.Builder(PaymentActivity.this)
                        .setTitle(getString(R.string.hint))
                        .setMessage(getString(R.string.order_error_hint))
                        .setNegativeButton(getString(R.string.pay_again), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                launchActivity(AboutOrderTypeActivity.class, AboutOrderTypeActivity.EXTRA_INDEX, 0);
//                                setResult(RESULT_OK);
//                                finish();
                            }
                        }).setPositiveButton(getString(R.string.pay_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                setResult(20001);
                                PaymentActivity.this.finish();
                            }
                        });
                alert.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
            resumeType = 2;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onBackClicked(View v) {
        if (paymentBean.getIsBatch() == 1) {
            showAlert();
        } else {
            super.onBackClicked(v);
        }
    }

    @Override
    public void onBackPressed() {
        if (paymentBean.getIsBatch() == 1) {
            showAlert();
        } else {
            super.onBackPressed();
        }
    }

    private void showAlert() {
        new AlertDialog.Builder(mActivity)
                .setTitle(getString(R.string.hint))
                .setMessage(getString(R.string.order_not_pay_are_you_sure_back_pressed_page))
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setResult(20001);
                        finish();
                    }
                }).setNegativeButton(getString(R.string.cancel), null).show();
    }

    /**
     * 输入支付密码的回调
     */
    @Override
    protected void dispatchOnActivityForResultEvent(int requestCode, int resultCode, Intent data) {
        super.dispatchOnActivityForResultEvent(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_INPUT_PAY_PASSWORD://输入支付密码
            {
                if (resultCode == RESULT_OK) {
                    showProgressCircle(getString(R.string.please_waiting_pay));
                    String password = data.getStringExtra(PaymentPasswordInputActivity.EXTRA_PASSWORD);
                    homeRequest.payOfKeKangAn(paymentBean.getOrderNo(), password, TokenManager.getInstance().getTokeValue(), MAKE_SURE_THE_ORDER_PAYMENT_SUCCESSFUL);
                }
                if (resultCode == 20001) {
                    dismissProgressCircle();
                    tvPay.setClickable(true);
                }
            }
        }
    }
}
